#!/usr/bin/env python
import rospy
from std_msgs.msg import String
import logging

class LogToTopic:
    def __init__(self, topic_name='/ros_log'):
        self.pub = rospy.Publisher(topic_name, String, queue_size=10)
        
        self.logger = logging.getLogger('rosout')
        self.handler = self.RosLogHandler(self.pub)
        self.logger.addHandler(self.handler)
        self.logger.setLevel(logging.INFO)
    
    class RosLogHandler(logging.Handler):
        def __init__(self, publisher):
            logging.Handler.__init__(self)
            self.publisher = publisher
        
        def emit(self, record):
            msg = String()
            msg.data = record.getMessage() if hasattr(record,'getMessage') else record.msg
            self.publisher.publish(msg)
    
    def shutdown(self):
        self.logger.removeHandler(self.handler)